package com.gjy.spring.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author gjy
 * @version 1.0
 * @since 2025-02-18 10:14:25
 */
@RestController
@RequestMapping("/api")
public class GetApiController {

    @Autowired
    private WebApplicationContext applicationContext;

    @GetMapping("/exportAllApi")
    public List<Map<String, String>> exportApis() {
        List<Map<String, String>> resultList = new ArrayList<>();
        RequestMappingHandlerMapping mapping = applicationContext.getBean(RequestMappingHandlerMapping.class);
        Map<RequestMappingInfo, HandlerMethod> methodMap = mapping.getHandlerMethods();

        for (Map.Entry<RequestMappingInfo, HandlerMethod> entry : methodMap.entrySet()) {
            Map<String, String> apiInfo = new LinkedHashMap<>();
            RequestMappingInfo info = entry.getKey();
            HandlerMethod handlerMethod = entry.getValue();

            // 获取类信息
            apiInfo.put("className", handlerMethod.getBeanType().getName());
            // 获取方法名
            apiInfo.put("methodName", handlerMethod.getMethod().getName());
            // 获取请求路径
            Set<String> paths = info.getPatternsCondition().getPatterns();
            apiInfo.put("path", String.join(",", paths));
            // 获取请求方法类型
            Set<RequestMethod> methods = info.getMethodsCondition().getMethods();
            apiInfo.put("method", methods.stream().map(Enum::name).collect(Collectors.joining(",")));

            resultList.add(apiInfo);
        }
        return resultList;
    }

    @GetMapping("/exportUrls")
    public Set<String> exportUrls() {
        Set<String> urls = new HashSet<>();
        RequestMappingHandlerMapping mapping = applicationContext.getBean(RequestMappingHandlerMapping.class);

        mapping.getHandlerMethods().keySet().forEach(info -> {
            Set<String> patterns = info.getPatternsCondition().getPatterns();
            urls.addAll(patterns);
        });

        return urls.stream()
                .map(url -> "http://localhost:8080" + url) // 替换实际域名
                .collect(Collectors.toSet());
    }

}
